import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header


def sendEmail():
    # 设置smtplib所需的参数
    # smtp服务器网址
    smtpserver = 'smtp.163.com'
    # 个人账号
    username = 'a13376640689@163.com'
    # smtp授权码
    password = 'XYFNNDKJATYWFBCV'
    # 发送方邮件地址
    sender = 'a13376640689@163.com'
    # 接收方邮件地址
    # ,'1047831253@qq.com','1282647260@qq.com','1832759755@qq.com','1264361002@qq.com'
    receivers = ['1435423375@qq.com','a13376640689@163.com']
    # receivers = ['a13376640689@163.com','1435423375@qq.com','1047831253@qq.com','1282647260@qq.com',
    #             '1832759755@qq.com','1264361002@qq.com','925449850@qq.com','596057579@qq.com',
    #             '2461129283@qq.com','1029378887@qq.com','2272248493@qq.com']
    # 中文需要通过Header对象编码进行转译
    subject = '青年之声新活动提醒'
    subject = Header(subject, 'utf-8').encode()

    # 构造邮件对象MIMEMultipart对象
    # 下面的主题，发件人，收件人，日期是显示在邮件页面上的。
    msg = MIMEMultipart('mixed')
    msg['Subject'] = subject
    msg['From'] = sender+" <"+sender+">"
    if len(receivers) == 1:
        msg['To'] = receivers[0]
    else:
        # 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
        msg['To'] = ";".join(receivers)

    # 构造文字内容
    openText = open('txt/dayNews.txt','r')
    sendText = openText.read()
    if len(sendText) != 0:
        text_plain = MIMEText(sendText, 'plain', 'utf-8')
    else:
        return
    msg.attach(text_plain)
    openText.close()

    # 构造附件
    openFile = open(r'txt/news.txt', 'rt')
    sendfile = openFile.read()
    text_att = MIMEText(sendfile, 'base64', 'utf-8')
    text_att["Content-Type"] = 'application/octet-stream'
    # 重命名附件
    text_att["Content-Disposition"] = 'attachment; filename="AllActivity.txt"'
    msg.attach(text_att)
    openFile.close()

    # 发送邮件
    smtp = smtplib.SMTP_SSL(smtpserver, 465)
    # smtp.connect(smtpserver)
    smtp.login(username, password)
    smtp.sendmail(sender, receivers, msg.as_string())
    smtp.quit()
